/*
 * Importer.fx
 *
 * Created on 15-Feb-2009, 01:24:01
 */

package logic;

import javafx.io.http.HttpRequest;
import java.lang.Exception;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.lang.StringBuffer;

/**
 * @author beol
 */

public class Importer {
    def request:HttpRequest = HttpRequest {

        location: "http://ya.ru";

        onStarted: function() { println("started") }
        onConnecting: function() { println("connecting...") }
        onDoneConnect: function() { println("doneConnect") }
        onReadingHeaders: function() { println("readingHeaders...") }
        onResponseCode: function(code:Integer) { println("responseCode: {code}") }
        onResponseMessage: function(msg:String) { println("responseMessage: {msg}") }

        onResponseHeaders: function(headerNames: String[]) {
                println("there are {headerNames.size()} response headers:");
            for (name in headerNames) {
                println("    {name}: {request.getResponseHeaderValue(name)}");
            }
        }

        onToRead: function(bytes: Integer) { println("bytes to read: {bytes}") }
        onRead: function(bytes: Integer) {
            def progress = if (request.toread > 0) "({(bytes * 100 / request.toread)}%)" else "";
            println("bytes read: {bytes} {progress}");
        }

        onInput: function(is: java.io.InputStream) {
            try {
                println("bytes of content available: {is.available()}");
                var bf:BufferedReader = new BufferedReader(new InputStreamReader(is, "CP1251"));
                var temp: StringBuffer = new StringBuffer();
                while(bf.ready()) {
                    temp.append(bf.readLine());
                    //temp.append("\n");
                }

                } finally {
                    is.close();
            }
        }

        onException: function(ex: Exception) { println("exception: {ex.toString()}") }
        onDoneRead: function() { println("doneRead") }
        onDone: function() { println("done") }
    }

}
